package com.linmo.chatmanage;

import com.linmo.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ChatManage {

    private static final Logger log = LoggerFactory.getLogger(ChatManage.class);

    //创建新的会话
    public int createSession(int userId) {
        try (Connection conn = DBUtil.getConnection()){
            String sql = "INSERT INTO history_sessions (user_id, update_time) VALUES (?,?)";
            PreparedStatement statement = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            statement.setInt(1, userId);
            statement.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
            statement.executeUpdate();

            // 获取自增主键（会话id）
            ResultSet rs = statement.getGeneratedKeys();
            if (rs.next()) {
                log.info("创建会话成功:{}", rs.getInt(1));
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            log.error("创建会话失败", e);
            throw new RuntimeException(e);
        }
        return 0;
    }

    //结束会话
    public void endSession(int sessionId) {
        try (Connection conn = DBUtil.getConnection()){
            String sql = "UPDATE history_sessions SET update_time = ? WHERE id = ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
            statement.setInt(2, sessionId);
            statement.executeUpdate();
        } catch (SQLException e) {
        log.error("结束会话出错", e);
        throw new RuntimeException(e);
    }
    }

    // 加载历史记录（会话区）
    public List<SessionRecordDTO> loadSessionMessages(int sessionId) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT role, message FROM session_records WHERE session_id = ? ORDER BY created_time";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, sessionId);
            ResultSet rs = statement.executeQuery();

            // 提取 ResultSet 数据到 List
            List<SessionRecordDTO> resultList = new ArrayList<>();
            while (rs.next()) {
                String role = rs.getString("role");
                String message = rs.getString("message");

                resultList.add(new SessionRecordDTO(sessionId, role, message));
            }

            log.info("加载会话记录成功:{}", resultList);
            return resultList;

        } catch (SQLException e) {
            log.error("加载会话记录出错", e);
            throw new RuntimeException(e);
        }

    }

}
